package org.tangjl.utill.itext;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 使用iText将HTML转成PDF
 * 可以使用CSS字符串,也可以使用单独的CSS文件,但是直接将CSS放在HTML中不会有效果
 * @author tangjialin on 2016-01-21 0021.
 */
public class ConverterUtil {
	public static final String CSS = "body { font-family: \"微软雅黑\"; font-size: 14px; }\n" +
			"p { line-height: 25px; text-indent: 28px; }\n" +
			"h2 { text-align: center; font-size: 16px; font-weight: bold; margin-bottom: 20px; }";

	public static void main(String[] args) throws Exception {
		// System.getProperty("user.dir")/src/org/tangjl/utill/itext/
		String basePath = ConverterUtil.class.getPackage().getName().replaceAll("\\.", "/") + "/";
		basePath = System.getProperty("user.dir") + "/src/" + basePath;
		InputStream htmlFile = new FileInputStream(basePath + "demo.html");
		// 使用css样式
//		InputStream cssFile = new ByteArrayInputStream(CSS.getBytes());
		// 或者可以用CSS文件
		InputStream cssFile = new FileInputStream(basePath + "demo.css");
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(basePath + "demo.pdf"));
		document.open();
		XMLWorkerHelper.getInstance().parseXHtml(writer, document, htmlFile, cssFile);
		document.close();
		writer.close();
		cssFile.close();
		htmlFile.close();
	}
}
